package org.jeecg.modules.hc.controller;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.hc.entity.HcOrder;
import org.jeecg.modules.hc.entity.HcOrderDetailed;
import org.jeecg.modules.hc.entity.HcOrderMerchant;
import org.jeecg.modules.hc.enums.HcSystemConfKeyEnum;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.utils.HcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Api(tags = "订单")
@RestController
@RequestMapping("/hc/hcOrder")
@Slf4j
public class HcOrderController extends JeecgController<HcOrder, IHcOrderService> {
    @Autowired
    private IHcOrderService hcOrderService;

    @Autowired
    private IHcSystemConfService hcSystemConfService;

    @Autowired
    private IHcOrderDetailedService hcOrderDetailedService;

    @Autowired
    private IHcOrderMerchantService hcOrderMerchantService;

    @Autowired
    private IHcUserService hcUserService;

    @Autowired
    private IHcAliPayService hcAliPayService;

    @Autowired
    private IHcWxPayService hcWxPayService;

    @ApiOperation("下单")
    @PostMapping("/createOrder")
    public Result<?> createOrder(@Validated @RequestBody HcOrder param) throws WxPayException, AlipayApiException {


        hcWxPayService.pay(param.getWxPayType(), param.getUserId(), "", "用膳团", null);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        param.setUserId(sysUser.getId());

        Map<String, String> allSystemConf = hcSystemConfService.getAllSystemConf();
        String begin = allSystemConf.get(HcSystemConfKeyEnum.MORNING_TIME_BEGIN.getValue());
        String end = allSystemConf.get(HcSystemConfKeyEnum.MORNING_TIME_END.getValue());
        boolean nowBetweenHHmmss1 = HcUtils.nowBetweenHHmmss(begin, end);

        String begin2 = allSystemConf.get(HcSystemConfKeyEnum.AFTERNOON_TIME_BEGIN.getValue());
        String end2 = allSystemConf.get(HcSystemConfKeyEnum.AFTERNOON_TIME_END.getValue());
        boolean nowBetweenHHmmss2 = HcUtils.nowBetweenHHmmss(begin2, end2);

        if (!nowBetweenHHmmss1 && !nowBetweenHHmmss2) {
            return Result.error("平台打烊中不能下单");
        }

        return Result.ok(hcOrderService.pay(param));
    }

    @ApiOperation("查询支付结果")
    @PostMapping("/queryResult")
    public Result<?> queryResult(@RequestBody HcOrder param) throws AlipayApiException, WxPayException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        param.setUserId(sysUser.getId());
        return Result.ok(hcOrderService.queryResult(param));
    }

    @ApiOperation("/查询PC-WX支付结果")
    @GetMapping("/queryRes")
    public Result<?> queryWXRes(@RequestParam(name = "outTradeNum")String outTradeNum) throws WxPayException {
        return Result.ok(hcOrderService.queryNativePay(outTradeNum));
    }

    @ApiOperation("/查询PC-支付宝支付结果")
    @GetMapping("/queryAliPayRes")
    public Result<?> queryAliPayRes(@RequestParam(name = "outTradeNum")String outTradeNum) throws AlipayApiException {
        return Result.ok(hcAliPayService.queryAliPayRes(outTradeNum));
    }
    /**
     * 分页列表查询
     *
     * @param hcOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "订单-分页列表查询")
    @ApiOperation(value = "订单-分页列表查询", notes = "订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcOrder>> queryPageList(HcOrder hcOrder,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<HcOrder> queryWrapper = QueryGenerator.initQueryWrapper(hcOrder, req.getParameterMap());
        Page<HcOrder> page = new Page<HcOrder>(pageNo, pageSize);
        IPage<HcOrder> pageList = hcOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcOrder
     * @return
     */
//	@AutoLog(value = "订单-添加")
//	@ApiOperation(value="订单-添加", notes="订单-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_order:add")
//	@PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcOrder hcOrder) {
        hcOrderService.save(hcOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcOrder
     * @return
     */
//	@AutoLog(value = "订单-编辑")
//	@ApiOperation(value="订单-编辑", notes="订单-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_order:edit")
//	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody HcOrder hcOrder) {
        hcOrderService.updateById(hcOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//	@AutoLog(value = "订单-通过id删除")
//	@ApiOperation(value="订单-通过id删除", notes="订单-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_order:delete")
//	@DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//	@AutoLog(value = "订单-批量删除")
//	@ApiOperation(value="订单-批量删除", notes="订单-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_order:deleteBatch")
//	@DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "订单-通过id查询")
    @ApiOperation(value = "订单-通过id查询", notes = "订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        HcOrder hcOrder = hcOrderService.getById(id);
        if (hcOrder == null) {
            return Result.error("未找到对应数据");
        }

        //获取下单的菜品名称
        HcOrderDetailed hcOrderDetailed = hcOrderDetailedService.getOne(new QueryWrapper<HcOrderDetailed>()
                .select("GROUP_CONCAT(TRADE_NAME Separator '+') as tradeName")
                .eq("ORDER_ID", hcOrder.getId())
        );

        HcOrderMerchant hcOrderMerchant = hcOrderMerchantService.getOne(new LambdaQueryWrapper<HcOrderMerchant>()
                .eq(HcOrderMerchant::getOrderId, hcOrder.getId())
                .last(" limit 1 ")
        );

        hcOrder.setNameDishes(hcOrderDetailed.getTradeName())
                .setPickingSerialNo(hcOrderMerchant.getPickingSerialNo())
                .setAddressId(hcOrderMerchant.getAddressId())
                .setPickingAddress(hcOrderMerchant.getPickingAddress());

        return Result.OK(hcOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcOrder
     */
    //@RequiresPermissions("org.jeecg.modules:hc_order:exportXls")
//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcOrder hcOrder) {
        return super.exportXls(request, hcOrder, HcOrder.class, "订单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_order:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcOrder.class);
    }

}
